Golang : Set or add headers for many or different handlers
Problem :
In Golang, setting headers can be done easily with the Set() method.
At the moment, you are setting headers for each individual handler in such as manner :
func handlerA(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler B."))
}
Instead of setting header for each individual handler manually, you want to use a function to set the headers.
NOTE : This method can apply to Add headers as well
Solution :
Create a common SetHeaders()
function that will write to http.ResponseWriter. For example :
func SetHeaders(w http.ResponseWriter) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
}
func handlerA(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler B."))
}
See also : Golang : How to Set or Add Header http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.7k Golang : Test if an input is an Armstrong number example
+8.9k Golang : Accept any number of function arguments with three dots(...)
+5.8k Javascript : How to replace HTML inside <div>?
+8.6k Golang : Progress bar with ∎ character
+10k Golang : Convert octal value to string to deal with leading zero problem
+7.9k Javascript : Put image into Chrome browser's console
+9.6k Golang : How to extract video or image files from html source code
+8.7k Golang : How to join strings?
+9.6k Golang : Read file with ioutil
+9.3k Golang : Generate random Chinese, Japanese, Korean and other runes
+15.3k Golang : Get all local users and print out their home directory, description and group id
+24.5k Golang : Time slice or date sort and reverse sort example